﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ZiChen.SoXunLeiPan.Common
{
    public class HelpCode
    {
        /// <summary>
        /// 字节B转KB、MB、GB
        /// </summary>
        /// <param name="b"></param>
        /// <returns></returns>
        public static string ByteToString(long size)
        {
            if (size < 0)
                throw new ArgumentException("Size cannot be negative.", nameof(size));

            const long KB = 1024L;
            const long MB = KB * 1024L;
            const long GB = MB * 1024L;
            const long TB = GB * 1024L;

            double value;
            string unit;

            if (size >= TB)
            {
                value = Math.Round(size / (double)TB, 2);
                unit = "TB";
            }
            else if (size >= GB)
            {
                value = Math.Round(size / (double)GB, 2);
                unit = "GB";
            }
            else if (size >= MB)
            {
                value = Math.Round(size / (double)MB, 2);
                unit = "MB";
            }
            else if (size >= KB)
            {
                value = Math.Round(size / (double)KB, 2);
                unit = "KB";
            }
            else
            {
                value = size;
                unit = "B";
            }

            return $"{value}{unit}";
        }
    }
}
